/**
 * @file ths_log.c  - 日志处理
 *
 * @verbatim
 * 修改历史
 *
 * 日期        		修改人                   		描述
 * 2018-01-04   Hansen          		初始化实现
 *
 * @endverbatim
 */

#include "ths_log.h"

static ths_log_level_t log_level = THS_LOG_LEVEL_DEBUG;
static byte_t log_is_trace_enabled = 0;
static byte_t log_is_debug_enabled = 1;
static byte_t log_is_info_enabled = 1;
static byte_t log_is_warn_enabled = 1;
static byte_t log_is_error_enabled = 1;

void ths_log_init(ths_log_level_t level) {
	log_level = level;

	log_is_trace_enabled = (THS_LOG_LEVEL_TRACE >= log_level) ? 1 : 0;
	log_is_debug_enabled = (THS_LOG_LEVEL_DEBUG >= log_level) ? 1 : 0;
	log_is_info_enabled = (THS_LOG_LEVEL_INFO >= log_level) ? 1 : 0;
	log_is_warn_enabled = (THS_LOG_LEVEL_WARN >= log_level) ? 1 : 0;
	log_is_error_enabled = (THS_LOG_LEVEL_ERROR >= log_level) ? 1 : 0;
}

byte_t ths_log_is_trace_enabled() {
	return log_is_trace_enabled;
}

byte_t ths_log_is_debug_enabled() {
	return log_is_debug_enabled;
}

byte_t ths_log_is_info_enabled() {
	return log_is_info_enabled;
}

byte_t ths_log_is_warn_enabled() {
	return log_is_warn_enabled;
}

byte_t ths_log_is_error_enabled() {
	return log_is_error_enabled;
}

static void ths_build_format_time(char *char_buf, size_t size) {
    time_t rawtime;
    struct tm *timeinfo = NULL;

    time(&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(char_buf, size,"%Y-%m-%d %H:%M:%S",timeinfo);
}

static const char *ths_build_log_level(ths_log_level_t level) {
	static const char log_level_uplower[][6] = {"TRACE", "DEBUG", "INFO", "WARN", "ERROR"};
	const char *level_pt = NULL;

	switch (level) {
		case THS_LOG_LEVEL_TRACE:
			level_pt = &log_level_uplower[0][0];
			break;
		case THS_LOG_LEVEL_DEBUG:
			level_pt = &log_level_uplower[1][0];
			break;
		case THS_LOG_LEVEL_INFO:
			level_pt = &log_level_uplower[2][0];
			break;
		case THS_LOG_LEVEL_WARN:
			level_pt = &log_level_uplower[3][0];
			break;
		case THS_LOG_LEVEL_ERROR:
			level_pt = &log_level_uplower[4][0];
			break;
		default:
			level_pt = "";
	}

	return level_pt;
}

void ths_log_msg(const char *file, const char *func, long line, ths_log_level_t level, const char *msg, ...) {
	va_list args;
	const char *level_str = NULL;
	char msg_buf[1024], time_buf[20];

	ths_build_format_time(time_buf, sizeof(time_buf));
	level_str = ths_build_log_level(level);

	va_start(args, msg);
	vsprintf(msg_buf, msg, args);
	va_end(args);

	printf("%s %-5s [%s:%ld] %s\n", time_buf, level_str, file, line, msg_buf);
}


